<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div class="sign-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="detailInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" @queryProcessData="queryProcessData" />
        <div v-loading="infoLoading" class="sign-detail-content small-padding">
          <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
          <div style="margin-bottom: 20px;">
            <Title title="基础信息" style="margin:0px 0 10px 0;"/>
            <el-form
              :class="{'mobile-el-form': showMobilePage}"
              :label-position="showMobilePage?'left':'right'"
              label-width="105px"
              class="abandon-form height55">
              <el-row :gutter="20" :class="{'dividing': !showMobilePage}">
                <el-col :span="12">
                  <el-form-item label="审批单号:" prop="examineId" style="margin-bottom: 0px;">
                    <div>{{ detailInfo.approvalNum || '--' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建时间:" prop="createDate" style="margin-bottom: 0px;">
                    <span v-if="detailInfo.createTime">{{ detailInfo.createTime | format('YYYY/MM/DD HH:mm') }}</span>
                    <span v-else>--</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建人:" prop="creator" style="margin-bottom: 0px;">
                    <CheckUserInfo v-if="detailInfo.creator" :label="detailInfo.creator" :user-id="detailInfo.creatorId" />
                    <div v-else>--</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属部门:" prop="departmentName" style="margin-bottom: 0px;">
                    <div>{{ detailInfo.subordinateDepartment || '--' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人:" prop="proposer" style="margin-bottom: 0px;">
                    <CheckUserInfo v-if="detailInfo.applicant" :label="detailInfo.applicant" :user-id="detailInfo.applicantId" />
                    <div v-else>--</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请部门:" prop="deptName" style="margin-bottom: 0px;">
                    <div>{{ detailInfo.applyDepartment || '--' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属公司:" prop="deptName" style="margin-bottom: 0px;">
                    <div>{{ detailInfo.company || '--' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="借款周期:" prop="deptName" style="margin-bottom: 0px;">
                    <div v-if="detailInfo.loanStartDate">{{ detailInfo.loanStartDate | format('YYYY/MM/DD') }} - {{ detailInfo.loanEndDate | format('YYYY/MM/DD') }}</div>
                    <span v-else>--</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="借款说明:" prop="abandonRemark" style="margin-bottom: 0px;">
                    <div class="flex-center">
                      <ToolTip :content="detailInfo.remark" placement="top-start"/>
                      <span v-if="canEdit" class="edit-remark" @click="openEditDialog">编辑</span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="借款金额(元):" prop="abandonRemark" style="margin-bottom: 0px;">
                    <PriceColumn
                      :real-val="detailInfo.amount"
                      :price="detailInfo.amount / 100" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划支付日期:">
                    <div class="flex-center">
                      <ToolTip :content="detailInfo.planPaymentDate | format('YYYY/MM/DD')" />
                      <span v-if="canEditPlanPaymentDate" class="edit-btn" @click="showPlanPaymentDialog('plan')">编辑</span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="实际支付日期:">
                    <div class="flex-center">
                      <ToolTip :content="detailInfo.actualPaymentDate | format('YYYY/MM/DD')" />
                      <span v-if="canEditPlanPaymentDate" class="edit-btn" @click="showPlanPaymentDialog('actual')">编辑</span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="附件:" prop="attachment" style="margin-bottom: 0px;">
                    <div class="ellipsis">
                      <FileShowList v-if="detailInfo.attachment && detailInfo.attachment.length" :file-list="detailInfo.attachment" style="max-width:100%;" is-show-single-file />
                      <span v-else>--</span>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div style="position: relative;">
            <Title title="收款账户" style="margin:16px 0 10px 0"/>
            <el-table
              :data="accountInfo"
              style="width: 100%">
              <el-table-column
                prop="payName"
                label="收款户名">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.payName" class="cell-span" />
                </template>
              </el-table-column>
              <el-table-column
                prop="payNum"
                label="收款账号">
                <template slot-scope="scope">
                  <SecretText
                    v-if="stepActiveId === PROGRESS_STEP.FINISHED || isRevoke"
                    :log-text="`借款申请${detailInfo.approvalNum}收款账户${scope.row.payName}的收款账号`"
                    :origin-text="scope.row.payNum" />
                  <ToolTip v-else :content="scope.row.payNum" class="cell-span" />
                </template>
              </el-table-column>
              <el-table-column
                prop="bank"
                label="银行">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.bank" placement="top-start"/>
                </template>
              </el-table-column>
              <el-table-column
                prop="province"
                label="省市" />
              <el-table-column
                prop="subBank"
                label="支行" />
            </el-table>
          </div>
        </div>
        <ExamineAndApprove
          ref="examineAndApproveRef"
          :disabled="infoLoading"
          :process-id="processId"
          :main-id="loanId"
          :version="version"
          :get-comments-api="getLoanComments"
          :comment-add-api="addLoanComment"
          :process-revocation-api="revokeLoanProcess"
          :process-recall-api="recallLoanProcess"
          :process-audit-api="auditLoanProcess"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.LOAN"
          :process-type="PROCESS_TYPE.LOAN"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-aduitor-list="[{id: detailInfo.applicantId, userName: detailInfo.applicant}]"
          :approval-module-type="APPROVAL_MODULE_TYPE.LOAN"
          :show-print="true"
          :print-data="detailInfo"
          :is-apply="isApply"
          redirect-url="/businessPage/loanDetail"
          detail-page-router-name="loanDetail"
          edit-page-router-name="loanEdit"
          @toBack="toBack"
          @setProcessData="setProcessData"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handlePressSend="handlePressSend"
          @handleCreateNew="handleCreateNew"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
          @handleModify="handleModify('loanEdit',{id: loanId},{remodifyId: processId})"
          @getHistoryDetail="getHistoryDetail"
          @setCurrentVersion="setCurrentVersion"
          @freshDetail="queryInfo"
          @handleCancelPress="handleCancelPress"
        />
        <ding-ding-dialog
          ref="pressSendDialogRef"
          :btn1="'确认加急'"
          :btn2="'取消'"
          :show-send-checkbox="false"
          :select-with-user-load="false"
          :default-list="pressDefaultList"
          redirect-url="/businessPage/loanDetail"
          summary-title="加急原因"
          title="催办通知"
          @handelOK="toSend" />
        <editDialog ref="descriptionEdit" :edit-api="editLoanRemark" :id="loanId" title="编辑借款说明" @updateInfo="queryInfo"/>
        <PlanPaymentDialog
          ref="planPaymentDialogRef"
          :curr-date="currDate"
          :title="dialogTitle"
          @confirm="editPlanPaymentDate"
        />
      </template>
      <DeniedPlaceholder v-else />
    </div>
  </div>
</template>
<script>
// 组件
import ListTab from '@/components/ListTab';
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import Title from '@/components/Title';
import explanation from '@/components/Common/explanation';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import FileShowList from '@/components/CreateOrder/fileShowList';
import editDialog from '../payBack/components/editDialog';
import PlanPaymentDialog from '@/components/Common/planPaymentDialog';
// 工具函数
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { hasRouteAuth } from '@/utils/permission';
import { BUSINESS_TYPE, PROCESS_TYPE } from '@/utils/const/process';
import { format } from '@/filters/date';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
// API
import { getLoanDetail, getLoanComments, addLoanComment, revokeLoanProcess,
  recallLoanProcess, auditLoanProcess, editLoanRemark } from '@/api/loan';
import { planPaymentDateEdit } from '@/api/common';
import schedule from '@/mixins/schedule';
import revokeImg from '@/assets/auditProcess/process_status_3.png';
import { EVENT_TYPE, FIXED_PROCESS_TYPE } from '@/utils/const/process';

export default {
  components: {
    ListTab, ProgressStep, Title,
    explanation, ExamineAndApprove,
    FileShowList, editDialog,
    PlanPaymentDialog
  },
  filters: { format },
  mixins: [schedule],
  data() {
    return {
      APPROVAL_MODULE_TYPE,
      revokeImg,
      BUSINESS_TYPE, PROCESS_TYPE,
      processId: '', // 流程id
      detailInfo: {},
      infoLoading: false,
      permissionDenied: false, // 详情页是否可查看
      PROGRESS_STEP,
      // api
      revokeLoanProcess,
      addLoanComment,
      getLoanComments,
      recallLoanProcess,
      auditLoanProcess,
      editLoanRemark,
      stepActiveId: PROGRESS_STEP.PENDING,
      isRevoke: false,
      loanId: '', // 借款单id
      accountInfo: [],
      processData: {
        list: []
      },
      dialogTitle: '计划支付日期',
      editDateType: 'plan' // 当前编辑的时间是什么。 plan:计划支付时间 actual:实际支付时间
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    currDate() {
      return this.editDateType === 'plan' ? this.detailInfo.planPaymentDate : this.detailInfo.actualPaymentDate;
    },
    createUser() {
      let user = { id: this.detailInfo.creatorId, userName: this.detailInfo.creator };
      if (this.userInfo.id === this.detailInfo.creatorId) {
        user = this.userInfo;
      }
      return user;
    },
    isApprover() { // 是否为当前节点审批人
      const processList = this.processData.list;
      if (!processList || processList.length === 0) return false;
      let item = null;
      // nodeStatus 节点状态: 0:结束 1:进行中 2:未审批
      for (let i = 0; i < processList.length; i++) {
        if (!item && processList[i].nodeStatus === 1) {
          item = processList[i];
          break;
        }
      }
      if (!item || item.length === 0) return false;
      let userList = [];
      item.items.forEach(i => {
        userList = userList.concat(i.users);
      });
      return userList.some(i => i.id === this.userInfo.id);
    },
    canEdit() {
      return this.isApprover && this.detailInfo.hasEditEvent && this.isCurrentVersion;
    },
    canEditPlanPaymentDate() { // 是否可编辑计划支付日期
      const eventList = this.processData.operation && this.processData.operation.setEvents || [];
      return this.isApprover && eventList.includes(EVENT_TYPE.OPEN_PAY_TIME) && this.isCurrentVersion;
    },
    isApply() { // 申请人
      const proposerId = this.detailInfo && this.detailInfo.applicantId ? this.detailInfo.applicantId : '';
      return proposerId && this.userInfo.id === proposerId;
    }
  },
  created() {
    this.initData();
  },
  mounted() {
    if (this.$route.query.openComment) {
      this.$refs.examineAndApproveRef.isShowProcess = true;
    }
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.loanId = this.$route.query.id;
      this.processId = this.$route.query.processId;
      if (!this.loanId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    setProcessData(processData) {
      this.processData = processData;
    },
    // 获取基本信息
    queryInfo() {
      this.infoLoading = true;
      getLoanDetail({ id: this.loanId }).then(res => {
        this.handleProcessCheck(res.data.processId);
        this.handleDetailData(res);
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.infoLoading = false;
      });
    },
    // 处理详情接口返回的数据
    handleDetailData(res) {
      this.infoLoading = false;
      if (res.code === 200) {
        this.commentCount = res.data.commentCount;
        if (res.data.processStatus === 3) { // 3为撤销
          this.stepActiveId = PROGRESS_STEP.PENDING;
          this.isRevoke = true;
        } else {
          this.stepActiveId = res.data.processStatus;
          this.isRevoke = false;
        }
        this.accountInfo = res.data.accountInfo;
        this.detailInfo = res.data;
      }
    },
    queryProcessData() {
      this.queryInfo();
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
      });
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'loan' });
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    openEditDialog() {
      this.$refs.descriptionEdit.openDialog(this.detailInfo.remark);
    },
    showPlanPaymentDialog(type) {
      this.editDateType = type;
      if (type === 'actual') {
        this.dialogTitle = '实际支付日期';
      } else {
        this.dialogTitle = '计划支付日期';
      }
      this.$refs['planPaymentDialogRef'].dialogVisible = true;
    },
    // 计划支付日期编辑
    editPlanPaymentDate(val) {
      const params = {};
      params.id = this.loanId;
      params.moduleType = FIXED_PROCESS_TYPE.BORROW_APPLY;
      if (this.editDateType === 'plan') {
        params.planPaymentDate = val;
        params.actualPaymentDate = this.detailInfo.actualPaymentDate;
      } else {
        params.planPaymentDate = this.detailInfo.planPaymentDate;
        params.actualPaymentDate = val;
      }
      planPaymentDateEdit(params).then(res => {
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.queryInfo();
        }
      });
    },
    handleCreateNew() {
      const routeUrl = this.$router.resolve({
        name: 'loanEdit',
        params: { id: this.loanId },
        query: { reapplyId: this.processId, createNew: 1 }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
	.sign-detail-container{
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding-bottom: 55px;
    min-height: calc(100vh - 64px);
		.sign-detail-content{
      position: relative;
			padding: 16px 24px 56px;
      .edit-btn {
        color: #406EFF;
        margin-left: 4px;
        cursor: pointer;
      }
		}
    &::v-deep {
      .dividing{
        .el-col {
          padding-right: 0 !important;
          .el-form-item__content {
            border-right: 1px solid #EBEEFD;
          }
          &:nth-child(2n) {
            .el-form-item__content {
              border-right: none;
            }
          }
          &:last-child {
            .el-form-item__content {
              border-right: none;
            }
          }
        }
        .el-col:nth-child(even) {
          padding-left: 0 !important;
        }
      }
      .explanation-container{
        .explanation{
          padding-left: 32px!important;
        }
      }
    }
    .revoke-img{
      position: absolute;
      width: 80px;
      height: 80px;
      right: 56px;
      top: 33px;
      z-index: 999;
    }
    .list-tab{
      padding: 0 0 0 10px !important;
      &::v-deep {
        .item-content{
          padding: 16px 0 8px 0 !important;
        }
      }
    }
    .edit-remark{
      display: inline-block;
      min-width: 30px;
      margin-left: 10px;
      cursor: pointer;
      color:#406eff;
    }
    .account-header{
      display: flex;
      margin: 32px 0 16px;
      .title-tip{
        font-weight: normal;
        color: #999;
        font-size: 14px;
        margin: 0 4px 0 6px;
      }
      &::v-deep {
        .el-radio{
          display: flex;
          align-items: center;
        }
        .el-radio__label{
          color: #333333;
          padding-left: 4px;
        }
      }
    }
    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-top: 30px;
      .text {
        font-size: 14px;
        font-weight: 400;
        text-align: left;
        color: #999999;
        line-height: 20px;
        margin-top: 10px;
      }
      .blue {
        color: #406ef4;
      }
      img {
        width: 120px;
      }
    }
	}
  .list-tab{
    padding: 0 !important;
  }
	::v-deep .el-drawer {
			min-width: 300px;
		}
		::v-deep .el-form-item__label {
			color: #999;
		}
		::v-deep .el-form-item {
			margin-bottom: 0 !important;
		}
		::v-deep .explanation {
			margin-bottom: 0;
		}
</style>
